import logging
import os

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

from api_test.common.api_response import JsonResponse
from api_server.utils import *

from websocket import create_connection

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。

game_message_info = {}
pb2parse("mergical", os.path.dirname(os.path.abspath(__file__)) + "/proto/game_server_message.proto", game_message_info)


class MergicalGame(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['url', 'body'],
        properties={
            'url': openapi.Schema(type=openapi.TYPE_STRING, description="url地址 eg.ws://xxx.com/ws"),
            'body': openapi.Schema(type=openapi.TYPE_OBJECT, description="请求参数"),
            'login': openapi.Schema(type=openapi.TYPE_OBJECT, description="请求参数，body参数依赖的登录请求参数"),
        },
    ))
    def post(self, request):
        """
        mergical websocket+protobuf
        """
        # {"url":"ws://10.0.114.199:10101/ws"}
        # {"login": {"name": 1001,"echo": 0,"srv_id": 1,"uid": 125461,"time": 1567406149,"nonce": 15,"sign": "bbb2673c0092d9cda4b30310555aa85c","bi_paras": "{\"id_fv\":\"\",\"user_id\":\"\"}"}
        # {"body": {"name": "QCheck","security": {"deviceId":"1213123123131231","userId":""}}}
        try:
            data = JSONParser().parse(request)

            # url = data['protocol'] + "://" + data["ip"] + data["port"] + data["path"]
            url = data['url']
            ws = create_connection(url)
            assert ws.status == 101

            trans_name = data["body"]["name"]
            # TODO
            if trans_name not in ["QLogin"] and 'login' not in data:
                data["login"] = {"name":"QLogin","type":"guest","choose":1,"security":{"deviceId":"1213123123131231","userId":""}}

            if "login" in data:
                login_data = pb2seria(game_message_info, data["login"])
                ws.send_binary(login_data)
                ws.recv()

            body_data = pb2seria(game_message_info, data["body"])
            ws.send_binary(body_data)

            game_message_list = []
            while True:
                body_res = ws.recv()

                resp_name = "RTaskHang"
                game_message = eval(game_message_info[str(resp_name)])()
                game_message.ParseFromString(body_res)

                real_resp_name = game_message.name
                print(real_resp_name)

                game_message = eval(game_message_info[str(real_resp_name)])()
                game_message.ParseFromString(body_res)

                game_message_dict = pb2dict(game_message)
                print(game_message_dict)
                game_message_list.append(game_message_dict)
                if game_message.name == "R"+trans_name[1:]:
                    break
            return JsonResponse(data={"data": game_message_list, "status": ws.status}, code="999999", msg="成功")
        except Exception as e:
            return JsonResponse(code="999990", msg="失败", data={"error": str(e)})
